<template>
  <div class="add-base-info" v-loading="loading">
    <el-form
      size="small"
      label-width="100px"
      label-position="left"
      :model="form"
      :rules="rules"
      :disabled="!is_edit ? true : false"
    >
      <el-form-item :label="['','赛事名称','活动名称','任务名称'][type]" prop="name">
        <el-input :placeholder="'请输入'+['','赛事名称','活动名称','任务名称'][type]" v-model="form.name"></el-input>
      </el-form-item>
      <el-form-item :label="['','赛事封面','活动封面','任务封面'][type]" prop="cover">
        <div class="active-cover-box">
          <div class="add-active-cover">
            <img
              :src="$oss_url + form.cover + '?x-oss-process=image/resize,h_300'"
              alt="活动封面"
              v-if="form.cover"
            />
            <div class="add-cover-empty">
              <img
                src="https://ykp-new.oss-cn-hangzhou.aliyuncs.com/9525523d3131b88e30f2b8d37d89f69.png"
                alt
              />
              <div>请上传封面，格式：16:9`</div>
            </div>
          </div>
          <div class="add-cover-memo">
            <div class="add-cover-btn" @click="uploadCover">
              <i class="el-icon-upload2"></i>上传封面
              <!-- <input
                type="file"
                class="add-cover-file"
                @change="upCover($event)"
                v-if="is_edit"
              />-->
            </div>
            <p class="add-cover-notice">温馨提示</p>
            <p class="add-cover-notice-txt">1、图片宽高比：16：9，.jpg 或 .png格式，不超过 4M</p>
            <p class="add-cover-notice-txt">2、精美海报有助于增加报名量，并有机会获得强力推荐！</p>
          </div>
        </div>
      </el-form-item>
      <el-form-item label="报名时间" v-if="type == 2">
        <el-radio-group v-model="form.enter" @change="changeEnter">
          <el-radio :label="0">活动前均可报名</el-radio>
          <el-radio :label="1">自定义报名时间</el-radio>
        </el-radio-group>
        <div v-if="form.enter == 1" style="margin-top:10px;">
          <el-date-picker
            v-model="sign_start"
            type="datetime"
            placeholder="选择开始时间"
            value-format="timestamp"
            format="yyyy-MM-dd HH:mm"
            @change="changeSignStart"
          ></el-date-picker>
          <span style="padding:0 10px">至</span>
          <el-date-picker
            v-model="sign_end"
            type="datetime"
            placeholder="选择结束时间"
            value-format="timestamp"
            format="yyyy-MM-dd HH:mm"
            @change="changeSignEnd"
          ></el-date-picker>
        </div>
      </el-form-item>
      <el-form-item label="报名时间" v-if="type != 2" prop="active_time">
        <el-date-picker
          v-model="sign_start"
          type="datetime"
          placeholder="选择开始时间"
          value-format="timestamp"
          format="yyyy-MM-dd HH:mm"
          @change="changeSignStart"
        ></el-date-picker>
        <span style="padding:0 10px">至</span>
        <el-date-picker
          v-model="sign_end"
          type="datetime"
          placeholder="选择结束时间"
          value-format="timestamp"
          format="yyyy-MM-dd HH:mm"
          @change="changeSignEnd"
        ></el-date-picker>
      </el-form-item>
      <el-form-item :label="['','赛事时间','活动时间','任务时间'][type]" prop="active_time">
        <!-- <el-date-picker
          v-model="form.active_time"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="timestamp"
          @change="changeStartTime"
        ></el-date-picker>-->
        <el-date-picker
          v-model="ac_start"
          type="datetime"
          placeholder="选择开始时间"
          value-format="timestamp"
          format="yyyy-MM-dd HH:mm"
          @change="changeAcStart"
        ></el-date-picker>
        <span style="padding:0 10px">至</span>
        <el-date-picker
          v-model="ac_end"
          type="datetime"
          placeholder="选择结束时间"
          value-format="timestamp"
          format="yyyy-MM-dd HH:mm"
          @change="changeAcEnd"
        ></el-date-picker>
      </el-form-item>
      <el-form-item :label="['','比赛地点','活动地点','任务地点'][type]" prop="address">
        <el-input placeholder="请选择地点" v-model="form.address" readonly>
          <template slot="append">
            <div class="select-addr" @click="changeAddr()">选择地址</div>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item :label="['','比赛类型','活动类型','任务类型'][type]" prop="active_type">
        <el-select v-model="form.active_type">
          <el-option
            v-for="(item,key) in active_type"
            :key="key"
            :value="item.value"
            :label="item.label"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="报名范围" prop="active_limit">
        <el-select v-model="form.active_limit">
          <el-option
            v-for="(item,key) in active_obj"
            :key="key"
            :value="item.value"
            :label="item.label"
          ></el-option>
        </el-select>
      </el-form-item>
    </el-form>

    <el-dialog :visible.sync="crop_img" title="图片剪裁" width="800px">
      <div style="height:500px;">
        <vueCropper
          ref="cropper2"
          :img="example2.img "
          :outputSize="example2.size"
          :info="example2.info"
          :canScale="example2.canScale"
          :autoCrop="example2.autoCrop"
          :autoCropWidth="example2.autoCropWidth"
          :autoCropHeight="example2.autoCropHeight"
          :fixed="example2.fixed"
          :fixedNumber="example2.fixedNumber"
          :enlarge="4"
        ></vueCropper>
      </div>
      <div style="margin-top:10px">
        <span style="margin-bottom:10px;">上传进度：</span>
        <div style="height:5px;"></div>
        <el-progress :text-inside="true" :stroke-width="16" :percentage="up_process"></el-progress>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button class="com-btn" size="small" icon="el-icon-scissors" @click="finshCrop">裁剪并上传</el-button>
      </span>
    </el-dialog>
    <!-- 上传封面 -->
    <el-dialog :visible.sync="upload_model" width="800px" title="上传图片">
      <el-tabs v-model="upload_index">
        <el-tab-pane label="本地图片" name="0">
          <div class="upload-box-div">
            <i class="el-icon-upload"></i>
            <span>点击上传图片</span>
            <input type="file" class="add-cover-file" @change="upCover($event)" v-if="is_edit" />
          </div>
        </el-tab-pane>
        <el-tab-pane label="线上图片" name="1">
          <div class="line-img-box">
            <el-row :gutter="10">
              <el-col :span="8" v-for="(item,key) in upload_img_arr">
                <div class="up-img-box-select">
                  <img :src="$oss_url+item+'?x-oss-process=image/resize,h_300'" />
                  <div class="up-select-model">
                    <el-button class="com-btn" size="mini" @click="selectImg(key)">选择</el-button>
                  </div>
                </div>
              </el-col>
            </el-row>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>
  </div>
</template>

<script>
import selectAddr from "./select-addr.vue";
import { VueCropper } from "vue-cropper";

export default {
  components: { selectAddr, VueCropper },
  props: { active_id: {}, type: {}, is_edit: {} },
  data() {
    return {
      upload_model: false,
      upload_index: "0",
      upload_img_arr: [
        "/active/cover/2019/12/21/11_55_33_203.jpg",
        "/active/cover/2019/12/21/13_28_11_23.jpg",
        "/active/cover/2019/12/21/13_22_2_902.jpg",
        "/manage/111111111.jpg",
        "/manage/2222222.jpg",
        "/manage/3333.jpg"
      ],
      form: {
        name: "",
        enter: 0,
        enter_time: ["", ""],
        active_time: ["", ""],
        cover: "",
        active_type: 1,
        active_limit: -1,
        address: "",
        longitude: "",
        latitude: "",
        province: "",
        city: ""
      },
      sign_start: "",
      sign_end: "",
      ac_start: "",
      ac_end: "",
      rules: {
        name: [{ required: true, message: "请输入活动名称", trigger: "blur" }],
        cover: [{ required: true, message: "请输入活动名称", trigger: "blur" }],
        active_time: [
          { required: true, message: "请选择活动时间", trigger: "blur" }
        ],
        address: [
          { required: true, message: "请选择活动地址", trigger: "blur" }
        ],
        active_type: [
          { required: true, message: "请选择活动类型", trigger: "blur" }
        ],
        active_limit: [
          { required: true, message: "请选择报名范围", trigger: "blur" }
        ]
      },
      active_type: [
        { value: 1, label: "马拉松" },
        { value: 2, label: "越野跑" },
        { value: 3, label: "铁人三项" },
        { value: 4, label: "健康跑" },
        { value: 5, label: "徒步" },
        { value: 6, label: "定向跑" },
        { value: 7, label: "其他" }
      ],

      active_obj: [
        { value: -1, label: "所有人" },
        { value: 0, label: "跑团会员" },
        { value: 1, label: "高级会员" }
      ],
      example2: {
        //img的路径自行修改
        img: require("../../../assets/images/11.jpg"),
        info: true,
        size: 1,
        canScale: true,
        autoCrop: true,
        // 只有自动截图开启 宽度高度才生效
        autoCropWidth: 300,
        autoCropHeight: 600,
        fixed: true,
        // 真实的输出宽高
        infoTrue: true,
        fixedNumber: [16, 9]
      },
      crop_img: false,
      img_type: "",
      up_process: 0,
      loading: false
    };
  },
  mounted() {
    this.changeActiveType();
    if (this.active_id > 0) this.getData();
  },
  methods: {
    //选择图片
    selectImg(key) {
      this.form.cover = this.upload_img_arr[key];
      this.upload_model = false;
    },
    //上传封面
    uploadCover() {
      if (!this.is_edit) return false;
      this.upload_model = true;
    },
    //活动类型改变事件
    changeActiveType() {
      if (this.type == 1) {
        this.form.enter = 1;
        this.active_type = [
          { value: 1, label: "马拉松" },
          { value: 2, label: "越野跑" },
          { value: 3, label: "铁人三项" },
          { value: 4, label: "健康跑" },
          { value: 5, label: "徒步" },
          { value: 6, label: "定向跑" },
          { value: 7, label: "其他" }
        ];
      }
      if (this.type == 2) {
        this.active_type = [
          { value: 1, label: "约跑" },
          { value: 2, label: "组队参赛" },
          { value: 3, label: "培训" },
          { value: 4, label: "聚餐" },
          { value: 5, label: "旅行" },
          { value: 7, label: "其他" }
        ];
      }
      if (this.type == 3) {
        this.active_type = [
          { value: 1, label: "奖励" },
          { value: 2, label: "招募" },
          { value: 7, label: "其他" }
        ];
      }
    },
    //选择活动开始时间
    changeAcStart() {
      var timestamp = Date.parse(new Date());
      if (this.type != 3) {
        if (this.ac_start < timestamp) {
          this.toast(0, "活动开始时间不能小于当前时间");
          this.ac_start = "";
          return;
        }
        if (this.sign_end && this.ac_start < this.sign_end) {
          this.toast(0, "活动时间不能小于报名时间");
          this.ac_start = "";
          return;
        }
        if (this.ac_end && this.ac_start > this.ac_end) {
          this.toast(0, "活动开始时间不能大于结束时间");
          this.ac_start = "";
          return;
        }
      }else{
        if (this.sign_start && this.ac_start < this.sign_start) {
          this.toast(0, "任务开始时间不能小于报名时间");
          this.ac_start = "";
          return;
        }
      }

      this.form.active_time[0] = this.ac_start;
    },
    //选择活动结束时间
    changeAcEnd() {
      var timestamp = Date.parse(new Date());
      if (this.ac_end < timestamp) {
        this.toast(0, "活动开始结束不能小于当前时间");
        this.ac_end = "";
        return;
      }
      if (this.ac_start && this.ac_end < this.ac_start) {
        this.toast(0, "活动结束时间不能小于活动开始时间");
        this.ac_end = "";
        return;
      }
      if (this.sign_end && this.ac_end < this.sign_end) {
        this.toast(0, "活动结束时间不能小于报名时间");
        this.ac_end = "";
        return;
      }
      if (this.sign_start && this.ac_end < this.sign_start) {
        this.toast(0, "活动结束时间不能小于报名时间");
        this.ac_end = "";
        return;
      }
      this.form.active_time[1] = this.ac_end;
    },
    //选择报名开始时间
    changeSignStart() {
      var timestamp = Date.parse(new Date());
      if (this.ac_start && this.sign_start > this.ac_start) {
        this.toast(0, "报名时间不能大于活动时间");
        this.sign_start = "";
        return;
      }
      if (this.sign_end && this.sign_start > this.sign_end) {
        this.toast(0, "报名开始时间不得大于结束时间");
        this.sign_start = "";
        return;
      }
      console.log(this.form.enter_time);
      this.form.enter_time[0] = this.sign_start;
      var tem =
        this.sign_start > timestamp
          ? this.sign_start + 24 * 60 * 60 * 1000
          : timestamp + 24 * 60 * 60 * 1000;
      this.sign_end = tem;
    },
    //选择报名结束时间
    changeSignEnd() {
      var timestamp = Date.parse(new Date());
      if (this.sign_end < timestamp) {
        this.toast(0, "报名结束时间不得小于当前");
        this.sign_end = "";
        return;
      }
      if (this.sign_start && this.sign_end < this.sign_start) {
        this.toast(0, "报名结束时间不得小于开始时间");
        this.sign_end = "";
        return;
      }
      if (this.ac_start && this.sign_end > this.ac_start) {
        this.toast(0, "报名结束时间不得大于活动开始时间");
        this.sign_end = "";
        return;
      }
      this.form.enter_time[1] = this.sign_end;
    },
    /**
     * 获取获取基本信息
     */
    getData() {
      this.loading = true;
      this.ajaxs("active/getBaseInfo", {
        data: { id: this.active_id },
        success: res => {
          var data = res.msg;
          this.form = {
            id: data.id,
            name: data.name,
            enter: data.sign_up_type,
            enter_time: [data.sign_up_start * 1000, data.sign_up_end * 1000],
            active_time: [data.start_time * 1000, data.end_time * 1000],
            cover: data.cover,
            active_type: data.active_type,
            active_limit: data.active_limit,
            address: data.address,
            longitude: data.longitude,
            latitude: data.latitude,
            type: data.type,
            state: data.state
          };
          this.sign_start = data.sign_up_start + "000";
          this.sign_end = data.sign_up_end + "000";
          this.ac_start = data.start_time + "000";
          this.ac_end = data.end_time + "000";
          console.log(this.form);
          this.loading = false;
        }
      });
    },
    /**
     * 更改报名时间类型
     */
    changeEnter() {
      // this.form.active_time = "";
      this.form.enter_time = ["", ""];
    },
    /**
     * 更改报名时间
     */
    changeEnterTime(e) {
      if (e == null) return false;
      if (this.form.active_time[0]) {
        if (this.form.enter_time[1] > this.form.active_time[0]) {
          this.toast(0, "报名时间不能大于活动时间");
          this.form.enter_time = "";
        }
      } else {
        this.form.active_time = [e[1] + 1000, e[1] + 2000];
      }
    },
    /**
     * 修改活动时间
     */
    changeStartTime(e) {
      if (e == null) return false;
      if (e[0] < this.form.enter_time[1]) {
        this.toast(0, "活动时间必须大于报名时间");
        this.form.active_time = "";
      }
    },
    /**
     * 选择地址
     */
    changeAddr() {
      if (!this.is_edit) return false;
      this.$layer.iframe({
        content: {
          content: selectAddr, //传递的组件对象
          parent: this, //当前的vue对象
          data: {} //props
        },
        area: ["800px", "600px"],
        title: "选择地址"
      });
    },
    //长传封面
    upCover(e) {
      var file = e.currentTarget;
      var img = file.files[0];

      if (img == undefined) return false;
      //获取文件后缀名
      var arr = img["name"].split(".");
      this.img_type = arr[1];
      //验证图片格式
      if (!/\.(gif|jpg|jpeg|png|GIF|JPG|PNG)$/.test(img.name)) {
        this.$message.error("请上传正确格式的图片");
        return false;
      }
      var kb = 1024; //1KB字节数
      var mb = 1025 * 1024; //1mb字节数
      //验证图片大小
      if (img.size > 4 * mb) {
        this.$message.error("图片大小不能超过4M");
        return false;
      }

      var reader = new FileReader();
      reader.onload = evt => {
        //this.img_src = evt.target.result;
        // this.$emit('change',this.img_src);
        this.example2.img = evt.target.result;
        this.crop_img = true;
        this.upload_model = false;
      };
      reader.readAsDataURL(file.files[0]);
    },
    /**
     * 确定裁剪
     *
     */
    finshCrop() {
      this.$refs.cropper2.getCropData(data => {
        let OSS = require("ali-oss");
        let client = new OSS({
          region: "oss-cn-hangzhou",
          //云账号AccessKey有所有API访问权限，建议遵循阿里云安全最佳实践，部署在服务端使用RAM子账号或STS，部署在客户端使用STS。
          accessKeyId: "LTAIWdxCuPiIzLfm",
          accessKeySecret: "z1zLih5CgWNkWfuzHj7SbpJKVdME2a",
          bucket: "ykp-new"
        });
        // client.options.endpoint.protocol = "https:";
        //获取当前时间
        var date = new Date();
        var file_name =
          date.getFullYear() +
          "/" +
          (date.getMonth() + 1) +
          "/" +
          date.getDate() +
          "/" +
          date.getHours() +
          "_" +
          date.getMinutes() +
          "_" +
          date.getSeconds() +
          "_" +
          date.getMilliseconds();
        let filename = "/active/cover/" + file_name + "." + this.img_type;
        let res_file = this.dataURLtoFile(data, "");
        let that = this;
        async function put() {
          try {
            //object-name可以自定义为文件名（例如file.txt）或目录（例如abc/test/file.txt）的形式，实现将文件上传至当前Bucket或Bucket下的指定目录。
            let result = await client
              .multipartUpload(filename, res_file, {
                progress: percentage => {
                  that.up_process = parseInt(percentage * 100);
                  //console.log(percentage); // 上传文件进度
                }
              })
              .then(res => {
                that.form.cover = res.name;

                setTimeout(() => {
                  that.crop_img = false;
                  setTimeout(() => {
                    that.up_process = 0;
                  }, 200);
                }, 500);
                //console.log(res);
              })
              .catch(err => {
                return that.toast(0, "上传失败");
              });
          } catch (e) {
            return that.toast(0, "上传失败");
          }
        }
        put();
      });
    },
    /**
     * base64转文件
     */
    dataURLtoFile(dataurl, filename) {
      let arr = dataurl.split(","),
        mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]),
        n = bstr.length,
        u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new File([u8arr], filename, { type: mime });
    }
  },
  watch: {
    form: {
      handler(v, o) {
        this.$emit("change", v);
      },
      deep: true
    },
    type: {
      handler(v, o) {
        this.changeActiveType();
      },
      deep: true
    },
    sign_end: {
      handler(v, o) {
        // var timestamp = Date.parse(new Date());
        // var tem = this.sign_end > timestamp ? parseInt(this.sign_end) + (24 * 60 * 60 * 1000) : timestamp + (24 * 60 * 60 * 1000)
        // this.ac_start = tem;

        this.form.enter_time[1] = this.sign_end;
      },
      deep: true
    },
    ac_end: {
      handler(v, o) {
        this.form.active_time[1] = this.ac_end;
      },
      deep: true
    },
    ac_start: {
      handler(v, o) {
        // var timestamp = Date.parse(new Date());
        // var tem = this.ac_start > timestamp ? parseInt(this.ac_start) + (24 * 60 * 60 * 1000) : timestamp + (24 * 60 * 60 * 1000)
        // this.ac_end = tem;
        this.form.active_time[0] = this.ac_start;
      },
      deep: true
    }
  }
};
</script>

<style>
.up-img-box-select {
  overflow: hidden;
  border-radius: 3px;
  position: relative;
  cursor: pointer;
  margin-bottom: 10px;
}
.up-img-box-select > img {
  width: 100%;
  display: block;
}
.up-select-model {
  position: absolute;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  top: 0;
  left: 0;
  z-index: 1;
  opacity: 0;
  transition: all 0.2s linear;
  text-align: center;
  line-height: 164px;
}
.up-img-box-select:hover .up-select-model {
  opacity: 1;
}
.line-img-box {
  min-height: 300px;
  background: #f4fafc;
  width: 100%;
  padding: 10px;
}
.upload-box-div {
  width: 100%;
  height: 300px;
  background: #f4fafc;
  line-height: 300px;
  text-align: center;
  position: relative;
  font-size: 18px;
  cursor: pointer;
  color: #aaa;
}
.upload-box-div i {
  margin-right: 10px;
}
.el-input-group__append {
  padding: 0;
}
.select-addr {
  width: 80px;
  height: 100%;
  text-align: center;
  cursor: pointer;
}
.active-cover-box {
  overflow: hidden;
}
.add-active-cover {
  width: 320px;
  height: 180px;
  background: #f1f1f1;
  overflow: hidden;
  float: left;
}
.add-active-cover > img {
  width: 100%;
  height: 100%;
}
.add-cover-empty {
  width: 100%;
  height: 100%;
}
.add-cover-empty > img {
  width: 60%;
  display: block;
  margin: 30px auto;
  margin-bottom: 0;
}
.add-cover-empty > div {
  text-align: center;
  color: #ccc;
  font-size: 12px;
}
.add-cover-memo {
  float: left;
  margin-left: 20px;
}
.add-cover-notice {
  color: #8a70c6;
  margin: 10px 0;
}
.add-cover-notice-txt {
  color: #999;
}
.add-cover-btn {
  width: 120px;
  background: #8a70c6;
  color: #fff;
  height: 34px;
  line-height: 34px;
  text-align: center;
  cursor: pointer;
  border-radius: 3px;
  position: relative;
}
.add-cover-btn > i {
  margin-right: 5px;
}
.add-cover-file {
  position: absolute;
  width: 100%;
  height: 100%;
  opacity: 0;
  top: 0;
  left: 0;
  cursor: pointer;
}
</style>